package com.ifreshwing.activity.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.ifreshwing.ParkSysApplication;
import com.ifreshwing.ainterface.Ipermissons;
import com.ifreshwing.userpark.R;
import com.ifreshwing.utils.SharedPreferencesUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lz on 2017/4/26.
 * 权限申请 api>23  需要动态获取权限
 *
 * @author lz
 */
public class BaseActivity extends FragmentActivity {

    Bundle bundle;
    Intent intent;
    Ipermissons ps_callback;

    //用户同意权限标识
    public static final int U_ALLOW = PackageManager.PERMISSION_GRANTED;
    //拒绝
    public static final int U_DENIED = PackageManager.PERMISSION_DENIED;
    /**
     * 已知权限列表
     * 如果申请的权限为当前权限集合等级为最高，那么只需要申请一个最高权限即可
     */
    //GPS权限
    public static final String P_GPS = Manifest.permission.ACCESS_FINE_LOCATION;
    //相机
    public static final String P_CAMERA = Manifest.permission.CAMERA;
    //内外置SD卡读写权限
    public static final String P_SD = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    //拨打电话权限
    public static final String P_CALL = Manifest.permission.CALL_PHONE;
    //读取手机信息
    public static final String P_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParkSysApplication.getInstance().addActivity(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == U_ALLOW) {
                    ps_callback.p_CallBack(permissions[0], 1);
                } else {
                    ps_callback.p_CallBack(permissions[0], -1);
                }
                break;

            case 200:
                List<String> a_permissions = new ArrayList<>();
                List<String> d_permissions = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == 0) {
                        a_permissions.add(permissions[i]);
                    } else {
                        d_permissions.add(permissions[i]);
                    }
                }
                if (a_permissions.size() == permissions.length) {
                    ps_callback.ps_CallBack(permissions, 1);
                } else {
                    String[] str_permissions = new String[d_permissions.size()];
                    d_permissions.toArray(str_permissions);
                    ps_callback.ps_CallBack(str_permissions, -1);
                }
                break;
        }

    }

    // 申请单个权限
    public void ApplyPermisson(String permissionName, Ipermissons callBack) {
        this.ps_callback = callBack;
        try {
            if (ActivityCompat.checkSelfPermission(this, permissionName) == U_DENIED) {
                ActivityCompat.requestPermissions(this, new String[]{permissionName}, 100);
            } else if (ActivityCompat.checkSelfPermission(this, permissionName) == U_ALLOW) {
                ps_callback.p_CallBack(permissionName, 0);
            } else {
                ps_callback.p_CallBack(permissionName, -1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //申请权限组
    public void ApplyPermissons(String[] permissonNames, Ipermissons callBack) {
        this.ps_callback = callBack;
        try {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < permissonNames.length; i++) {
                if ((ActivityCompat.checkSelfPermission(this, permissonNames[i]) == U_DENIED)) {
                    list.add(permissonNames[i]);
                }
            }
            if (list.size() > 0) {
                String[] rPermissons = new String[list.size()];
                list.toArray(rPermissons);
                ActivityCompat.requestPermissions(this, rPermissons, 200);
            } else ps_callback.ps_CallBack(permissonNames, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测登陆（未登录跳转到登陆页面）
     */
    public boolean checkLogin() {
        if (SharedPreferencesUtil.isLogin(this)) {
            return true;
        } else {
            startActivity(LoginActivity.class);
            return false;
        }
    }


    /**
     * 返回bundle实例
     *
     * @return
     */
    public Bundle getBundle() {
        if (bundle == null) {
            bundle = new Bundle();
        }
        return bundle;
    }

    /**
     * 清除band数据
     */
    public void clearBundle() {
        getBundle().clear();
    }

    /**
     * 拿到封装数据的bundle对象
     *
     * @return
     */
    public Bundle getBundleExtra() {
        return getIntent().getBundleExtra("bundle");
    }

    /**
     * 拿到bundle传递的String对象
     *
     * @param key
     * @return
     */
    public String getBundleExtraForKey(String key) {
        try {
            return getBundleExtra().getString(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 拿到bundle传递的String对象
     *
     * @param key
     * @return
     */
    protected String getBundleExtraForKey(Intent intent, String key) {
        return intent.getBundleExtra("bundle").getString(key);
    }

    /**
     * 拿到bundle传递的Serializable对象
     *
     * @param intent
     * @param key
     * @return
     */
    protected Serializable getSerializableBundleForKey(Intent intent, String key) {
        return intent.getBundleExtra("bundle").getSerializable(key);
    }

    /**
     * 隐藏软键盘
     *
     * @param view
     */
    protected void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 跳转activity
     *
     * @param cls    跳转的目标Activity
     * @param bundle 封装的数据
     */
    public void startActivity(Class<? extends Activity> cls, Bundle bundle) {
        intent = new Intent(this, cls);
        intent.putExtra("bundle", bundle);
        startActivity(intent);
        overridePendingTransition(R.animator.push_right_in, R.animator.push_right_out);
    }

    /**
     * 跳转activity
     *
     * @param c    跳转的目标Activity
     * @param flag 添加的flag
     */
    protected void startActivity(Class<? extends Activity> c, int flag) {
        intent = new Intent(this, c);
        intent.setFlags(flag);
        //加上SINGLE_TOP之后，会直接调用之前创建的activity而finish掉之间的activity
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        overridePendingTransition(R.animator.push_right_in, R.animator.push_right_out);
    }

    /**
     * 跳转activity
     *
     * @param cls 跳转的目标Activity
     */
    public void startActivity(Class<? extends Activity> cls) {
        intent = new Intent(this, cls);
        startActivity(intent);
        overridePendingTransition(R.animator.push_right_in, R.animator.push_right_out);
    }

    /**
     * 跳转activity
     *
     * @param cls         跳转的目标Activity
     * @param requestCode 请求码
     */
    public void startActivityForResult(Class<? extends Activity> cls, int requestCode) {
        intent = new Intent(this, cls);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.animator.push_right_in, R.animator.push_right_out);
    }

    /**
     * 跳转activity
     *
     * @param cls
     * @param requestCode
     * @param bundle
     */
    public void startActivityForResult(Class<? extends Activity> cls, int requestCode, Bundle bundle) {
        intent = new Intent(this, cls);
        intent.putExtra("bundle", bundle);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.animator.push_right_in, R.animator.push_right_out);
    }

    /**
     * 跳转activity
     *
     * @param cls        返回的目标Activity
     * @param resultCode 返回码
     * @param bundle     封装的数据
     */
    public void setResult(Class<? extends Activity> cls, int resultCode, Bundle bundle) {
        intent = new Intent(this, cls);
        intent.putExtra("bundle", bundle);
        setResult(resultCode, intent);
        finish();
    }

    /**
     * 跳转activity
     *
     * @param resultCode 返回码
     * @param bundle     封装的数据
     */
    public void setResult(int resultCode, Bundle bundle) {
        intent = new Intent();
        intent.putExtra("bundle", bundle);
        setResult(resultCode, intent);
        finish();
    }




}
